import 'package:flutter/material.dart';
import 'package:flutter_popup/flutter_popup.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:get/get.dart';
import 'package:wk_robot2/app/models/Devices.dart';
import 'package:wk_robot2/app/modules/componentview/controllers/IndexViewController.dart';
import 'package:wk_robot2/app/utils/CommonUtil.dart';
import 'package:wk_robot2/app/widget/CommonWidgets.dart';
import '../../../event/DataCallBack.dart';
import '../../../event/WkEventListener.dart';
import '../../../routes/app_pages.dart';
import '../../../style/app_colors.dart';
import '../../../utils/NetWorkUtil.dart';
import '../../../widget/tips.dart';
import '../../ActionSquares/views/action_squares_view3.dart';

class IndexViewView extends GetView<IndexViewController> {
  IndexViewView({super.key});


  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: AppColors.app_base_bgcolor_color,
      body:Stack(
        children: [
          Image.asset('assets/images/bg_home.webp',height: 470.h,fit: BoxFit.fill,width: Get.width),
          Container(
            padding: EdgeInsets.only(left: 30.w,right: 30.w),
            child: Obx(()=>ListView(
              children: [
                Stack( // 机器人绑定动画.
                  children: [
                    Container( //滑板.
                      margin: EdgeInsets.only(top:237.h),
                      child: Image.asset('assets/images/bg_mini_shelf.webp',width: 710.w),
                    ),
                    controller.localRobotList.value.length == 0 ?
                    Container(
                      margin: EdgeInsets.only(top:28.h),
                      child: Row(
                        children: [
                          Column(
                            children: [
                              Container( //机器人图片
                                child: Image.asset('assets/images/ic_mini_online.webp',width: 230.w, height: 250.h),
                              ),

                            ],
                          ),
                          Column(
                            children: [
                              Container(
                                margin: EdgeInsets.only(bottom: 30.h),
                                child: Column(
                                  children: [
                                    //你还没绑定机器人
                                    Text('你还没绑定机器人',style: TextStyle(fontSize: 28.sp,color: AppColors.dialogTextColor),),
                                    SizedBox(height: 16.h),
                                    GestureDetector(
                                      onTap: () {
                                        controller.bindRobot();
                                      },
                                      child: Container(
                                        width: 260.w,
                                        height: 72.h,
                                        padding: EdgeInsets.only(top: 15.h,bottom: 15.h),
                                        decoration: BoxDecoration(
                                          color: Colors.black,
                                          borderRadius: BorderRadius.all(Radius.circular(90)),
                                        ),
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: [
                                            Image.asset('assets/images/ic_bindding.webp',width: 48.w,height: 48.h),
                                            SizedBox(width: 14.w,),
                                            Text('开始绑定',style: TextStyle(fontSize: 30.sp, color: Colors.white))
                                          ],
                                        ),
                                      ),
                                    )


                                  ],
                                ),
                              )
                            ],
                          )

                        ],
                      ),
                    ) :
                    Container(
                      margin: EdgeInsets.only(top:28.h),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                            child: Column(
                              children: [
                                Container( //机器人图片
                                  child: Image.asset(controller.myrobots.value.isOnline ? 'assets/images/index_page_ic_mini_online.webp':
                                  'assets/images/ic_mini_offline.png',width: 230.w, height: 250.h),
                                ),

                              ],
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: 45.h),
                            child:  Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    Text('悟空机器人',style: TextStyle(fontSize: 48.sp)),
                                    SizedBox(width: 16.w),
                                    CustomPopup(
                                      content: showRobotsMenuList(),
                                      child: Row(
                                        children: [
                                          Text('${controller.robotNameElected.value}',style: TextStyle(fontSize: 30.sp)),
                                          SizedBox(width: 10.w),
                                          Image.asset('assets/images/ic_drop-down.webp',width: 24.w,height: 24.h)
                                        ],
                                      ),
                                      backgroundColor: AppColors.MAIN_MENUE_BG_COLOR.withOpacity(0.9),
                                      arrowColor: AppColors.MAIN_MENUE_BG_COLOR.withOpacity(0.9),
                                      contentPadding: EdgeInsets.all(5.w),
                                    ),

                                  ],
                                ),

                                controller.myrobots.value!.isOnline ?
                                Row(
                                  children: [
                                    Image.asset(controller.batteryIcon.value, width: 48.w,height: 48.h),
                                    SizedBox(width: 12.w,),
                                    Text('${controller.batteryCapacity.value}%',style: TextStyle(fontSize: 22.sp)),
                                    SizedBox(width: 23.w,),
                                    Image.asset(controller.wifiIcon.value,width: 48.w,height: 48.h),
                                    SizedBox(width: 12.w,),
                                    Text('${controller.myrobots.value.wifiName}',style: TextStyle(fontSize: 22.sp)),
                                  ],
                                ) :
                                Row(
                                  children: [
                                    Image.asset('assets/images/ic_warning_index_page.png',width: 36.w,height: 36.h),
                                    SizedBox(width: 8.w,),
                                    Text('机器人离线',style: TextStyle(fontSize: 28.sp)),
                                    SizedBox(width: 20.w,),
                                    GestureDetector(
                                      onTap: () {
                                          controller.bindRobot();
                                      },
                                      child: Container(
                                        padding: EdgeInsets.symmetric(horizontal: 23.w,vertical: 6.h),
                                        decoration: BoxDecoration(
                                          borderRadius: BorderRadius.circular(22),
                                          color: Colors.white.withOpacity(0.5),
                                        ),
                                        child: Text('切换Wi-Fi',style: TextStyle(fontSize: 28.sp)),
                                      ),
                                    )

                                  ],
                                )
                              ],
                            ),
                          )


                        ],
                      ),
                    )

                  ],
                ),
                Container(
                  height: 290.h,
                  child: GridView.builder(
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      // 交叉轴（通常是垂直方向）上的子项数量
                      crossAxisCount: 4,
                      // 子项之间的主轴（通常是水平方向）间距
                      mainAxisSpacing: 10.0.h,
                      // 子项之间的交叉轴（垂直方向）间距
                      crossAxisSpacing: 0.0,
                      // 子项在交叉轴（垂直方向）上的最小长度
                      childAspectRatio: 4.0 / 3.0,
                    ),
                    itemCount: controller.getRobotFunctionList().length,
                    itemBuilder: (BuildContext context, int index) {
                      Map<String,dynamic> item =
                      controller.getRobotFunctionList()[index];

                      return Wrap(
                        children: [
                          GestureDetector(
                            child: Center(
                              child: Column(
                                children: [
                                  Image.asset(item['icon'],width: 100.w, height: 100.h,),
                                  Text(item['name'],style: TextStyle(color: AppColors.Sub_Title_Color,fontSize: 24.sp),)
                                ],
                              ),
                            ),
                            onTap: () async {

                              List<Device> robotlists = CommonUtil.getMyRobotLists();
                              if (robotlists.isEmpty) {
                                CommonWidgets.showConfirmDialog(Get.context!,'请绑定悟空机器人',"绑定后可以使用各项技能","绑定","取消",
                                    DataCallBack(
                                        confirmCallBack: (v) {
                                          controller.bindRobot();
                                        },
                                        cancleCallBack: (v) {
                                          print('no ....');
                                        }
                                    )
                                );
                                return;
                              }

                              if (item['type'] != 'actionSquare' && item['type'] != 'readingCompany') {
                                   if(!CommonUtil.getCurrentSelectedRobot().isOnline) {
                                     CommonWidgets.showSingleBtnDialog(Get.context!, '', '机器人不在线，暂时无法使用此功能.', WkEventListener(
                                        onClick: (v) {

                                        }
                                     ));
                                     return;
                                   }
                              }


                              if (item['type'] == 'videoTalking') {
                                bool isNetWork = await NetWorkUtil.checkNetWorkIsAvailable();
                                if (!isNetWork) {
                                  CommonWidgets.showSingleBtnDialog(Get.context!, "", "手机无网络，无法开启视频通话",
                                      btnText: "知道了", WkEventListener(onClick: (v) {
                                      }));
                                  return;
                                }

                                if(CommonUtil.getCurrentSelectedRobot().isOnline && ((CommonUtil.getCurrentSelectedRobot().powerValue??0) < 20)){
                                  CommonWidgets.showSingleBtnDialog(Get.context!, "", "机器人电量过低，无法进行视频通话",
                                      btnText: "知道了", WkEventListener(onClick: (v) {
                                      }));
                                  return;
                                }
                                controller.gotoVideoLiveView();
                              } else if (item['type'] == 'actionSquare') {
                                // Get.toNamed(Routes.ACTION_SQUARES);
                                Navigator.of(context).push(
                                    MaterialPageRoute(builder: (context) => ActionSquaresView3())
                                );
                              } else if (item['type'] == 'readingCompany') {
                                Get.toNamed(Routes.READING_COMPANY);

                              }

                            },
                          )
                        ],
                      );
                    },
                  ),
                ),
                SizedBox(height: 56.h), //  video, audio.
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [ //
                        Container(
                          margin: EdgeInsets.only(left: 10.w),
                          child: Stack(
                            children: [
                              Container(
                                margin: EdgeInsets.only(top: 25.h),
                                child: CommonWidgets.getSmallALine(),
                              ),
                              Text('视频玩法',style: TextStyle(fontSize: 30.sp,fontWeight: FontWeight.w600),)
                            ],
                          ),
                        ),
                        SizedBox(height: 12.h,),
                        Image.asset('assets/images/ic_video_show.webp',width: 300.w,height: 200.h,)
                      ],
                    ),
                    SizedBox(width: 38.h),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [ //
                        Container(
                          margin: EdgeInsets.only(left: 10.w),
                          child: Stack(
                            children: [
                              Container(
                                margin: EdgeInsets.only(top: 25.h),
                                child: CommonWidgets.getSmallALine(),
                              ),
                              Text('语音指令',style: TextStyle(fontSize: 30.sp,fontWeight: FontWeight.w600))
                            ],
                          ),
                        ),
                        SizedBox(height: 12.h,),
                        Image.asset('assets/images/ic_voice_command.webp',width: 300.w,height: 200.h,)
                      ],
                    )

                  ],
                ),
                SizedBox(height: 24.h,),
                // 话术训练区.
                Container(
                  margin: EdgeInsets.only(left: 32.w),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Container(
                            padding: EdgeInsets.only(left: 30.w,top: 15.h,bottom: 15.h,right: 40.w),
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(40),
                                color: Colors.white,
                                boxShadow: [
                                  BoxShadow(
                                    color: Colors.black.withOpacity(0.1), // 阴影颜色
                                    spreadRadius: 2.w, // 阴影扩展半径
                                    blurRadius: 7.w, // 阴影模糊半径
                                    offset: Offset(0, 3), // 阴影偏移量（水平，垂直）
                                  ),
                                ]
                            ),
                            child: Row(
                              children: [
                                Image.asset('assets/images/ic_drinks.webp',width: 50.w, height: 50.h),
                                SizedBox(width: 18.w),
                                Text('悟空悟空，帮我点一杯美式',style: TextStyle(fontSize: 28.sp,color: AppColors.Page_Title_Color),)
                              ],
                            ),
                          ),
                          Container(
                            child: Image.asset('assets/images/ic_refresh.webp',width: 40.w, height: 40.h),
                          )


                        ],
                      ),
                      SizedBox(height: 24.h,),
                      Row(
                        children: [
                          Container(
                            padding: EdgeInsets.only(left: 30.w,top: 15.h,bottom: 15.h,right: 40.w),
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(40),
                                color: Colors.white,
                                boxShadow: [
                                  BoxShadow(
                                    color: Colors.black.withOpacity(0.1), // 阴影颜色
                                    spreadRadius: 2.w, // 阴影扩展半径
                                    blurRadius: 7.w, // 阴影模糊半径
                                    offset: Offset(0, 3), // 阴影偏移量（水平，垂直）
                                  ),
                                ]
                            ),
                            child: Row(
                              children: [
                                Image.asset('assets/images/ic_taxi.webp',width: 50.w, height: 50.h),
                                SizedBox(width: 18.w),
                                Text('悟空悟空，帮我打车到公司',style: TextStyle(fontSize: 28.sp,color: AppColors.Page_Title_Color))
                              ],
                            ),
                          )
                        ],
                      ),
                      SizedBox(height: 24.h,),
                      Row(
                        children: [
                          Container(
                            padding: EdgeInsets.only(left: 30.w,top: 15.h,bottom: 15.h,right: 40.w),
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(40),
                                color: Colors.white,
                                boxShadow: [
                                  BoxShadow(
                                    color: Colors.black.withOpacity(0.1), // 阴影颜色
                                    spreadRadius: 2.w, // 阴影扩展半径
                                    blurRadius: 7.w, // 阴影模糊半径
                                    offset: Offset(0, 3), // 阴影偏移量（水平，垂直）
                                  ),
                                ]
                            ),
                            child: Row(
                              children: [
                                Image.asset('assets/images/ic_food.webp',width: 50.w, height: 50.h),
                                SizedBox(width: 18.w),
                                Text('悟空悟空，我要点外卖',style: TextStyle(fontSize: 28.sp,color: AppColors.Page_Title_Color))
                              ],
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 24.h,),
                      Row(
                        children: [
                          Container(
                            padding: EdgeInsets.only(left: 30.w,top: 15.h,bottom: 15.h,right: 40.w),
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(40),
                                color: Colors.white,
                                boxShadow: [
                                  BoxShadow(
                                    color: Colors.black.withOpacity(0.1), // 阴影颜色
                                    spreadRadius: 2.w, // 阴影扩展半径
                                    blurRadius: 7.w, // 阴影模糊半径
                                    offset: Offset(0, 3), // 阴影偏移量（水平，垂直）
                                  ),
                                ]
                            ),
                            child: Row(
                              children: [
                                Image.asset('assets/images/ic_hotel.webp',width: 50.w, height: 50.h),
                                SizedBox(width: 18.w),
                                Text('悟空悟空，查一下附近的酒店',style: TextStyle(fontSize: 28.sp,color: AppColors.Page_Title_Color))
                              ],
                            ),
                          )
                        ],
                      ),

                    ],
                  ),
                )
              ],


            )),
          )
        ],
      ),
    );
  }


  Widget showRobotsMenuList() {
    return Container(
      width: 540.w,
      // height: menueHeight.h, // 670.h
      padding: EdgeInsets.only(top: 16.h, bottom: 41.h, left: 30.w,right: 30.w),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          controller.localRobotList.value.length > 5 ?  Container(
              height: 500.h,
              child: ListView.separated(
                  itemCount: controller.localRobotList.value.length,
                  itemBuilder: (BuildContext context, int index) {
                    return renderItem(context,index);
                  },
                  separatorBuilder: (context, index) => Divider(color: Colors.white.withOpacity(0.2),height:2,thickness:0.5, indent: 6.0,endIndent: 6.0),
              )
          ) : Container(
            child: Column(
              children: controller.renderItemsForLess5(),
            ),
          ),
          SizedBox(height: 40.h),
          GestureDetector(
            onTap: () {
              Get.back();
              controller.bindRobot();

            },
            child: Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset('assets/images/ic_blind_blue_add_new_robot.webp',width: 48.w,height: 48.h),
                  SizedBox(width: 14.w,),
                  Text('绑定新悟空机器人',style: TextStyle(fontSize: 28.sp,color: Colors.white.withOpacity(0.8)))
                ],
              ),
            ),
          )


        ],
      ),
    );
  }

  Widget renderItem(BuildContext context, int index) {
    Device item = controller.localRobotList.value[index];
    return Container(
     
      padding: EdgeInsets.all(5),
      child: GestureDetector(
        onTap: () {
          controller.changeCurrentConnectionDevice(item);
          Get.back();
        },
        child: Container(
          color: Colors.white.withOpacity(0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Image.asset('assets/images/ic_avatar_online.png',width: 80.w,height: 80.h,),
                  SizedBox(width: 28.w,),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text('悟空',style: TextStyle(fontSize: 30.sp,color: Colors.white.withOpacity(0.8))),
                          SizedBox(width: 14.w),
                          Container(
                            padding: EdgeInsets.only(left: 13.w,right: 13.w),
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.all(Radius.circular(20)),
                                color: Colors.white
                            ),
                            child: Text(item.isOnline ? '在线': '离线',style: TextStyle(fontSize: 22.sp,fontWeight: FontWeight.bold,color: AppColors.Page_Title_Color),),
                          )
                        ],
                      ),
                      Text('${item.robotUserId}',style: TextStyle(fontSize: 24.sp,color: Colors.white.withOpacity(0.8)))

                    ],
                  )
                ],
              ),
              item.selected == true ? Image.asset('assets/images/ic_robots_selected.webp',width: 40.w,height: 40.h,color: Colors.white.withOpacity(0.8)) : SizedBox()
            ],
          ),
        ),
      ),
    );
  }
}
